<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-menu"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="addForm" ref="addForm" :rules="rules">
                    <el-form-item label="单位" prop="name" :label-width="formLabelWidth">
                        <el-input v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="链接地址" prop="url" :label-width="formLabelWidth">
                        <el-input v-model="addForm.url" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="栏目类型" prop="type" :label-width="formLabelWidth">
                        <el-select v-model="addForm.paternerTypeId" placeholder="请选择栏目类型">
                            <el-option v-for="(type,index) in types" :key="type.id" :label="type.name" :value="type.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
                        <el-input 
                            v-model="addForm.remark"   
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}" 
                            auto-complete="off"
                        >
                        </el-input>
                    </el-form-item>
                    <el-form-item label="链接图片" :label-width="formLabelWidth">
                        <el-upload 
                            class="avatar-uploader" 
                            ref="upload" 
                            action="" 
                            :http-request="uploadRequest"
                            :show-file-list="false" 
                            v-loading.fullscreen.lock="fullscreenLoading"
                        >
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </div>
            </el-dialog>
            <el-input v-model="select_word" placeholder="输入单位名" class="search"></el-input>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button type="primary" @click="beforeAdd">新增合作单位</el-button>
        </div>
        <div>
            <el-table :data="tableData" border fit style="width: 100%">
                <el-table-column prop="name" label="单位名称" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="图片">
                    <template slot-scope="scope">
                        <img :src="scope.row.img" width="100%" height="100%" />
                    </template>
                </el-table-column>
                <el-table-column prop="url" label="链接地址" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="paterner_type_id" label="类型" :formatter="type_format">
                </el-table-column>
                <el-table-column prop="remark" label="备注" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="state" label="状态" show-overflow-tooltip empty-text :formatter="stateFormatter">
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button type="text" size="small" @click="delFriend(scope.row)">删除</el-button>
                        <el-switch
                            v-model="scope.row.state === 1 ? true : false"
                            active-color="#13ce66"
                            @change="switchChange(scope.row)"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="block">
            <el-pagination @current-change="handleCurrentChange" 
            :current-page="page.number" layout="total, prev, pager, next, jumper" 
            :total="page.total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import { paterner, uploadFile } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
import { filterObj } from './../../utils/local.js'
const { listApi, addApi, updateApi, deleteApi, disableApi, allTypes } = paterner
export default {
    data() {
        return {
            value: '',
            loading: false,
            dialogTableVisible: false,
            dialogFormVisible: false,
            dialogFormUpdate: false,
            select_word: '',
            addForm: {
            },
            getLocation: location,
            formLabelWidth: '120px',
            title: '',
            fullscreenLoading: false,
            imageUrl: '',
            rules: {
                name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
            },
        }
    },
    created() {
        this.getTypeList()
        this.getFriends(1)
    },
    computed: mapState({
        tableData: state => state.Friend.list,
        page: state => state.Friend.page,
        types: state => state.Friend.typeList
    }),
    methods: {
        ...mapActions(['allFriends', 'saveType']),
        getTypeList(){
            allTypes().then(res => {
                if (res.code === '000000') {
                    this.saveType(res)
                } else {
                    this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        },
        getFriends(number) {
            const params = {
                page: number,
                pageSize: 10
            }
            if (this.select_word !== '') {
                params.searchKey = this.select_word
            }            
            listApi({ ...params })
                .then(res => {
                    if (res.code === '000000') {
                        this.allFriends({
                            ...res,
                            number
                        })
                    } else {
                        this.$message.error(res.message)
                    }
                }, err => this.$message.error('服务器异常'))
        },
        edit(row) {
            this.title = '修改合作单位'
            this.dialogFormVisible = true
            this.addForm = filterObj(row)
            if (this.addForm.img) {
                this.imageUrl = this.addForm.img
            }
        },
        stateFormatter(row) {
            const state = row.state
            return state === 1 ? '启用' : '禁用'
        },
        delFriend(row) {
            this.$confirm('此操作将永久删除该合作单位 , 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteApi({ ids: row.id })
                    .then(res => {
                        if (res.code === '000000') {
                            this.getFriends(this.page.number)
                            this.$message.success('删除成功')
                        } else {
                            this.$message.error(res.message)
                        }
                    }, () => this.$message.error('服务器异常'))
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        type_format(row) {
            let name = ''
            this.types.some(item => {
                if (item.id === row.paterner_type_id) {
                    name = item.name
                    return true
                }
            })
            return name
        },
        add() {
            this.addForm.img = this.imageUrl
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                    this.dialogFormVisible = false
                    if (this.addForm.id) {
                        updateApi({ ...this.addForm }).then(res => {
                            if (res.code === '000000') {
                                this.$message.success('修改成功')
                                this.getFriends(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, () => {
                            this.$message.error('网络错误')
                        })
                    } else {
                        addApi({ ...this.addForm }).then(res => {
                            if (res.code === '000000') {
                                this.$message.success('添加成功')
                                this.getFriends(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, () => {
                            this.$message.error('网络错误')
                        })
                    }
                }
            })
        },
        search() {
            this.getFriends(this.page.number)
        },
        beforeAdd() {
            this.title = "新增合作单位"
            this.dialogFormVisible = true
            this.addForm = {}
            this.imageUrl = ''
        },
        handleCurrentChange(val) {
            this.getFriends(val)
        },
        cancel() {
            this.dialogFormVisible = false
        },
        switchChange(row) {
            disableApi({
                ids: row.id,
                state: row.state ? '0' : '1'
            }).then(res => {
                if (res.code === '000000') {
                    this.$message.success('修改成功')
                    this.getFriends(this.page.number)
                } else {
                    this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        },
        uploadRequest(value) {
            const fm = new FormData()
            fm.append('fileName', value.file)
            fm.append('fileType', '1')
            uploadFile(fm, res => {
                this.fullscreenLoading = false
                if (res.code === '000000') {
                    this.imageUrl = res.result.storageName
                }
            }, err => {
                this.fullscreenLoading = false
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
